package com.homework.util;

import com.homework.filters.TPMonitorFilter;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class ReportStatus implements Runnable {
    protected double percent90 = 0.9;  //90分位
    protected double percent99 = 0.99; //99分位

    @Override
    public void run() {
        System.out.println("开始上报...");
        HashMap<String, TreeSet<TPMonitorFilter.Dimension>> statistics =  TPMonitorFilter.REQUEST_STATISTICS;

        //遍历hashmap
        Set<Map.Entry<String, TreeSet<TPMonitorFilter.Dimension>>> set = statistics.entrySet();
        for(Map.Entry<String, TreeSet<TPMonitorFilter.Dimension>> entry : set) {
            String service = entry.getKey();
            TreeSet<TPMonitorFilter.Dimension> value = entry.getValue();
            report(value, service);
        }

        System.out.println("==================================");
    }

    protected void report(TreeSet<TPMonitorFilter.Dimension> statistics, String service) {
        synchronized (statistics) {
            long startTime = System.currentTimeMillis() - 60 * 1000; //获取一分钟前的时间
            for (TPMonitorFilter.Dimension data : statistics) {
                if(data.sendTime < startTime) {
                    statistics.remove(data);
                }
            }

            int size = statistics.size();
            int percent90Point = (int)(size * percent90);
            int percent99Point = (int)(size * percent99);

            TPMonitorFilter.Dimension percent90PointData = null;
            TPMonitorFilter.Dimension percent99PointData = null;
            int counter = 1;
            for (TPMonitorFilter.Dimension data : statistics) {
                if(counter == percent90Point) {
                    percent90PointData = data;
                } else if(counter == percent99Point) {
                    percent99PointData = data;
                }
                counter++;
            }

            System.out.println("服务【" + service + "】最近一分钟运行结果：");
            System.out.println("  90分位点耗时：" + percent90PointData.spendTime + "毫秒");
            System.out.println("  99分位点耗时：" + percent99PointData.spendTime + "毫秒");
        }
    }
}
